package com.sumer.proxy.jdk.proxy.jdk.proxy;

import com.sumer.proxy.jdk.proxy.Transaction;
import com.sumer.proxy.jdk.service.StudentService;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class JDKProxy implements InvocationHandler {

    private final StudentService studentService;

    private final Transaction transaction;

    public JDKProxy(StudentService studentService, Transaction transaction) {
        this.studentService = studentService;
        this.transaction = transaction;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object result = null;
        if ("add".equals(method.getName())){
            transaction.begin();
            result = method.invoke(studentService, args);
            transaction.commit();
        }else {
            result = method.invoke(studentService, args);
        }
        return result;
    }
}
